package org.icnmasjid.member.webapp.action;

import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.icnmasjid.member.Constants;
import org.icnmasjid.member.util.CommonUtil;
import org.icnmasjid.member.util.DateUtil;
import org.icnmasjid.member.util.DesEncrypter;
import org.icnmasjid.member.webapp.action.BaseFormController;
import org.icnmasjid.member.model.Person;
import org.icnmasjid.member.model.PersonPayment;
import org.icnmasjid.member.model.PersonSubOrgRole;
import org.icnmasjid.member.model.Role;
import org.icnmasjid.member.model.SubOrg;
import org.icnmasjid.member.service.PersonManager;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import com.sun.mail.iap.Response;

public class MassEmailPersonController extends BaseFormController {

	private PersonManager personManager;

    public void setPersonManager(PersonManager personManager) {
        this.personManager = personManager;
    }

    public MassEmailPersonController() {
    	setCommandClass(Person.class);
    	setCommandName("person");
	}

    @Override
    protected boolean isFormSubmission(HttpServletRequest request) {
    	return true;
    }

    public ModelAndView onSubmit(HttpServletRequest request,
                                 HttpServletResponse response, Object command,
                                 BindException errors)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("entering 'onSubmit' method...");
        }
        Locale locale = request.getLocale();
        
    	String subject = request.getParameter("subject");
    	if ( StringUtils.isBlank(subject)) {
    		subject = "Important: ICN Membership Update";
    	}
    	String template = request.getParameter("template");
    	if ( StringUtils.isBlank(template)) {
    		template = "membership_update.vm";
    	}        
    	boolean debug = false;
    	String email = request.getParameter("email");    	
    	debug = StringUtils.isNotBlank(email);
    	
    	if ( debug )  {

            Map model = new HashMap();
            Person p = personManager.getPersonByEmail(email);
            model.put("person", p);
            model.put("passKey", URLEncoder.encode(new DesEncrypter(Constants.PASS_PHRASE).encrypt(""+p.getPersonId()),"UTF-8"));                    	
        	String message = mailEngine.getConvertedMessage(template, model);
        	System.out.println("*************");
        	System.out.println(message);
        	System.out.println("*************");
        	try {
        		mailEngine.sendMimeMessage(
        				template, 
        				model, 
        				"fmohamed@gmail.com", 
        				p.getEmails().toArray(new String[]{}), 
        				subject
        		);
        		/*
	        	CommonUtil.send(
	        			"admin@icnschool.com", 
	        			p.getEmails().toArray(new String[]{}), 
	        			null, 
	        			subject, 
	        			mailEngine.getConvertedMessage(template, model)
	        	);
	        	*/
        	} catch(Exception e) { 
        		e.printStackTrace();
        	}    		
    	} else {
	        List<Person> persons = personManager.getPrimaryPersonsWithEmail();
	        for ( Person p: persons) {
	        	// lets exclude persons who have already member
	        	if ( !p.isMember(2012) ) { 
		        	Integer primaryPersonId = p.getPersonId();	        	
	    			try {
	    	            Map model = new HashMap();
	    	            model.put("person", p);
	    	            model.put("passKey", URLEncoder.encode(new DesEncrypter(Constants.PASS_PHRASE).encrypt(""+p.getPersonId()),"UTF-8"));                    	
	    	        	try {
	    	        		mailEngine.sendMimeMessage(
	    	        				template, 
	    	        				model, 
	    	        				Constants.EMAIL_FROM, 
	    	        				p.getEmails().toArray(new String[]{}), 
	    	        				subject
	    	        		);
	    	        	} catch(Exception e) { 
	    	        		e.printStackTrace();
	    	        	}	    				
			            p.setEmailSent(new Timestamp(System.currentTimeMillis()));
			            personManager.savePerson(p);				    		
	    			} catch (Exception e) {
	    				logger.error("unable to send email to " + p.getEmail(), e);
	    			}
	        	}
	        } // end for
    	}
    	return new ModelAndView("importReport","result", "success");
    }
}
